package com.itxg.booksmanage.controller;

import com.itxg.booksmanage.common.R;
import com.itxg.booksmanage.entity.User;
import com.itxg.booksmanage.service.UserService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) {
        User query = userService.login(user);
        if (!ObjectUtils.isEmpty(query)) {
            // 如果返回不空，说明登录成功
            session.setAttribute("login", true); // 保存 Session
            session.setMaxInactiveInterval(180000);
            return R.success(query);
        }
        // 作废当前 Session
        session.invalidate();
        return R.error("账号或密码输入错误，登录失败");
    }

    @PostMapping("/regist")
    public R regist(@RequestBody User user) {
        int i = userService.regist(user);
        switch (i) {
            case 1:
                return R.success();
            case -2:
                return R.error("用户名已存在");
            default:
                return R.error("注册失败");
        }
    }

    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.invalidate(); // 作废 session
        return R.success("退出登录成功");
    }

    @PostMapping("/test")
    public R test(@RequestBody User user, HttpServletRequest request) {
        return R.success("Test success");
    }

}
